import random
import time

import serial

from loguru import logger


class Supply:
    def __init__(self, com: str, rate: int):
        self.com = com
        self.rate = rate
        self.ser = serial.Serial(com, rate)
    def close(self):
        self.ser.close()

    def _open_remote_control(self):
        self.ser.write('SYST:REM\n'.encode())

    def set_volt(self, value: float):
        while True:
            self._open_remote_control()
            self.ser.write(f'VOLT {value}\n'.encode())
            current_volt = self.get_volt(0)
            if abs(current_volt - value) > 0.1:
                logger.warning(f'设置电压{value}V失败，当前电压{current_volt}V')
            else:
                logger.info(f'设置电压{value}V成功')
                break

    def get_volt(self, i) -> float:
        self.ser.write(f'VOLT?\n'.encode())
        return float(self._read_serial())

    def get_curr(self) -> float:
        self.ser.write(f'MEAS:CURR?\n'.encode())
        return float(self._read_serial())

    def _read_serial(self) -> str:
        return self.ser.readline().decode()

    def _get_output(self) -> bool:
        self.ser.write(f'OUTP?\n'.encode())
        status = int(self._read_serial())
        return True if status == 1 else False

    def output(self, open_supply: bool = True):
        while True:
            self._open_remote_control()
            self.ser.write(f'OUTP {1 if open_supply else 0}\n'.encode())
            opt = self._get_output()
            prefix = '关闭' if not open_supply else '打开'
            if open_supply == opt:
                logger.info(f'{prefix}电源成功')
                break
            else:
                logger.warning(f'{prefix}电源失败')


if __name__ == '__main__':
    logger.add('../run.log')
    supply = Supply('COM4', 9600)

    for i in range(40):
        supply.set_volt(random.uniform(20, 24))
        supply.output(False)
        print(supply.get_curr())
        supply.output(True)
        print(supply.get_curr())
    supply.output(True)
    supply.set_volt(24)

